define(['jquery', 'bootstrap', 'utilback', 'table', 'form'], function ($, undefined, Utilback, Table, Form) {

    var Controller = {
    	config: {
    		get_url: '/seller/read/detail',
    	},
        init: function () {
            // 初始化表格参数配置
            Table.api.init({
            	singleSelect: true,
                extend: {
                    index_url: '/seller/read/list',
                    add_url: 'sellerEdit.html',
                    edit_url: 'sellerEdit.html',
                    del_url: '/seller',
                    multi_url: '/seller',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                columns: [
                    [
                        {field: 'state', checkbox: true, },
                        {field: 'id', title: 'ID'},
                        {field: 'sellerName', title: __('商家名称')},
                        {field: 'contactName', title: __('联系人')},
                        {field: 'mainBusiness', title: '主营类目'},
                        {field: 'sortNo', title: '排序'},
                        {field: 'enable', title: '审核状态', formatter: function (v, row, index) {
                        	return v == '0' ? '未审核' : v == '1' ? '审核通过' : '审核拒绝';
                        }},
                        {field: 'operate', title: __('Operate'), events: Table.api.events.operate, formatter: function (value, row, index) {
                                if(row.enable == 1) {
                                    return '';
                                }
                                return Table.api.formatter.operate.call(this, value, row, index, table);
                            }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        edit: function () {
            Form.api.bindevent($("form[role=form]"));
        	Util.api.initSelectOption({
            	target: '[name="license.licenseCountry"],[name="license.companyCountry"],[name="bank.bankCountry"]',
            	param: {type: 'COUNTRY'},
            	next: {
            		target: '[name="mainBusiness"],[name="subBusiness"]',
                	param: {type: 'MAINBUSINESS'},
                	next: {
                		target: '.taxpayerType',
                    	param: {type: 'TAXPAYERTYPE'},
                    	next: {
                    		target: '.taxpayerTypeCode',
                        	param: {type: 'TAXPAYERTYPECODE'},
                        	next: {
                        		target: '.businessType',
                            	param: {type: 'BRANDBUSINESSTYPE'},
                            	init: function() {
                            		init();
                            	}
                        	}
                    	}
                	}
            	}
            });
        	
        	function init() {
        		var id = Util.api.query('id');
                if(id) {
                	$('.OPT').text('编辑');
            		Form.api.fill($('#editForm'), Controller.config.get_url, id, function(data) {
        				$('[name="mainBusiness"]').selectpicker('val',data.mainBusiness);
	    		    	if(data.taxCertificate) {
	        				$('.taxpayerType').selectpicker('val',data.taxCertificate.taxpayerType);
	        				$('.taxpayerTypeCode').selectpicker('val',data.taxCertificate.taxpayerTypeCode);
	        	        	if(data.taxCertificate.eleCertificate)
	        	        		$('#taxCertificateEleCertificateContainer').parent().append('<img height="30px" src="'+data.taxCertificate.eleCertificate+'">');
	        	        	if(data.taxCertificate.eleTaxpayerCertificate)
	        	        		$('#taxCertificateEleTaxpayerCertificateContainer').parent().append('<img height="30px" src="'+data.taxCertificate.eleTaxpayerCertificate+'">');
	    		    	}
	    		    	$.each(['Province', 'City', 'Area'], function(i, v) {
	    		    		if(data['license' + v + 's']) {
			                    $('[name="license.license'+v+'"]').append('<option value="">--请选择--</option>');
	    		    			$.each(data['license' + v + 's'], function(n, value) {
				                    $('[name="license.license'+v+'"]').append('<option value="'+value.code+'">'+value.codeText+'</option>');
	    	 					});
	    		    		}
	    		    		if(data['company' + v + 's']) {
			                    $('[name="license.company'+v+'"]').append('<option value="">--请选择--</option>');
	    		    			$.each(data['company' + v + 's'], function(n, value) {
				                    $('[name="license.company'+v+'"]').append('<option value="'+value.code+'">'+value.codeText+'</option>');
	    	 					});
	    		    		}
	    		    		if(data['bank' + v + 's']) {
			                    $('[name="bank.bank'+v+'"]').append('<option value="">--请选择--</option>');
	    		    			$.each(data['bank' + v + 's'], function(n, value) {
				                    $('[name="bank.bank'+v+'"]').append('<option value="'+value.code+'">'+value.codeText+'</option>');
	    	 					});
	    		    		}
	    		    	});
	    		    	$.each(['Country', 'Province', 'City', 'Area'], function(i, v) {
	    			    	if(data.license) {
                				$('[name="license.license'+v+'"]').selectpicker('val', data.license['license'+v]);
                				$('[name="license.company'+v+'"]').selectpicker('val', data.license['company'+v]);
	    			    	}
	    			    	if(data.bank) {
                				$('[name="bank.bank'+v+'"]').selectpicker('val', data.bank['bank']);
	    			    	}
	    		    	});
	        	        if(data.license) {
	        	        	if(data.license.eleIdCard)
	        	        		$('#prevlicenseEleIdCard').append('<img height="30px" src="'+data.license.eleIdCard+'">');
	        	        	if(data.license.eleLicense)
	        	        		$('#prevlicenseEleLicense').append('<img height="30px" src="'+data.license.eleLicense+'">');
	        	        }
	        	        if(data.organization) {
	        	        	if(data.organization.eleCertificate)
	        	        		$('#prevorganizationEleCertificate').append('<img height="30px" src="'+data.organization.eleCertificate+'">');
	        	        }
    			    	if(data.bank) {
	        	        	if(data.bank.eleAccountLicence)
	        	        		$('#prevtaxCertificateEleCertificate').append('<img height="30px" src="'+data.bank.eleAccountLicence+'">');
    			    	}
	        	        if(data.brands) {
	    	    	        $.each(data.brands, function(i, v) {
	    	    	        	addBrand(v.id, v);
	    	    	        });
	        	        }
	        	        if(data.businesses) {
	        	        	$.each(data.businesses, function(i, v) {
	        	        		subBusinesses[v.typeI+v.typeIi] = {
	        	        				id: v.id,
	        	        				mainBusinessTxt: v.typeITxt, subBusinessTxt: v.typeIiTxt,
	        	        				typeI: v.typeI, typeIi: v.typeIi
	        	        		};
	        	        	});
	        	        	resetSubBusiness();
	        	        }
        				addEvent();
            	        if(localStorage.getItem('readonly') === 'Y') {
            	        	$('#companyEdit span>a').parent().hide();
            	        	$('#companyEdit input').attr('disabled', true);
            	        	$('#companyEdit select').attr('disabled', true);
            	        	$('#companyEdit textarea').attr('disabled', true);
            	        	$('#companyEdit button').hide();
                       		if(data.enable === '0') {
                       			$('#companyEdit #chkPass').show();
                       		}
            	        } else {
            	        	$('#companyEdit #chkPass').hide();
            	        }
                	});
                } else {
                	addEvent();
                    if(localStorage.getItem('readonly') === 'Y') {
        	        	$('#companyEdit span>a').parent().hide();
                    	$('#companyEdit input').attr('disabled', true);
                    	$('#companyEdit select').attr('disabled', true);
        	        	$('#companyEdit textarea').attr('disabled', true);
        	        	$('#companyEdit button').hide();
                    } else {
        	        	$('#companyEdit #chkPass').hide();
        	        }
                }
            }
        	
            function addEvent() {
                $.each(['license.license', 'license.company', 'bank.bank'], function(n, v) {
                    $('[name="' + v + 'Country"]').on('change', function() {
                    	if($(this).val().length > 0) {
                    		Util.api.initSelectOption({
                    			target: '[name="' + v + 'Province"]',
                    			param: { type:'PROVINCE', parentType: 'COUNTRY', parentCode:$(this).val()}
                    		});
                    	} else {
                    		$.each(['Province', 'City', 'Area'], function(m, t) {
            	 				$('[name="' + v + t + '"]').html('');
                    		});
                    	}
                    });
                    $('[name="' + v + 'Province"]').on('change', function() {
                    	if($(this).val().length > 0) {
                    		Util.api.initSelectOption({
            	            	target: '[name="' + v + 'City"]',
            	            	param: { type:'CITY', parentType: 'PROVINCE', parentCode:$(this).val()}
            	        	});
                    	} else {
                    		$.each(['City', 'Area'], function(m, t) {
            	 				$('[name="' + v + t + '"]').html('');
                    		});
                    	}
                    });
                    $('[name="' + v + 'City"]').on('change', function() {
                    	if($(this).val().length > 0) {
                    		Util.api.initSelectOption({
            	            	target: '[name="' + v + 'Area"]',
            	            	param: { type:'AREA', parentType: 'CITY', parentCode:$(this).val()}
            	        	});
            	    	} else {
            	 			$('[name="' + v + 'Area"]').html('');
            	    	}
                    });
                });
            }
            
            // 经营信息
            $('[name="subBusiness"]').on('change', function() {
            	var mainBusiness = $(this);
            	Util.api.ajax({
                	type: 'PUT',
             		url : '/dic/read/list',
             		data: JSON.stringify({type: 'SUBBUSINESS',parentType: 'MAINBUSINESS', parentCode: mainBusiness.val()})
            	}, function(rst) {
     				var html = $('<div class="form-group col-xs-12 col-sm-12 col-md-12 col-lg-12">');
     				$.each(rst.rows, function(n, d) {
     					html.append('<label class="checkbox-inline"><input type="checkbox" class="subBusiness" value="' + d.code + '">' + d.codeText + '</label>');
 					});
     				$('#subBusiness').html(html);
            	});
            });
            $('.allSubBusiness').on('click', function() {
            	$('.subBusiness').prop('checked', $(this).is(':checked'));
            });
            var subBusinesses = {};
            $('.add-business').on('click', function() {
            	var mainBusiness = $('[name="subBusiness"]').val();
            	var mainBusinessTxt = $('[name="subBusiness"]').find("option:selected").text();
            	$('.subBusiness:checked').each(function() {
                	var id = new Date().getTime();
            		subBusinesses[mainBusiness + $(this).val()] = {
            				id: id,
            				mainBusinessTxt: mainBusinessTxt, subBusinessTxt: $(this).parent().text(),
            				typeI: mainBusiness, typeIi: $(this).val()
            		};
            	});
            	resetSubBusiness();
            });
            function resetSubBusiness() {
            	$('.business-list tbody').html('');
            	$('[name="business"]').remove();
            	var i = 1;
            	$.each(subBusinesses, function(v, obj) {
            		if(obj) {
                    	var tr =  '<tr>';
                    	tr += '<td>' + (i++) + '</td>';
                    	tr += '<td>' + obj['mainBusinessTxt'] + '</td>';
                    	tr += '<td>' + obj['subBusinessTxt'] + '</td>';
                    	tr += '<td><button type="button" class="btn bg-teal del-subBusiness" data-id="'+obj.id+'" data-code="'
                    	+ obj['typeI'] + obj['typeIi']
            	        	+ '">删除</button></td></tr>';
                    	$('.business-list tbody').append(tr);
                    	// 添加到from
                    	var hidden = '<input type="hidden" id="'+obj.id+'" name="businesses" value="'+JSON.stringify(obj).replace(/\"/g, '&quot;')+'"/>';
                    	$('#editForm').append(hidden);
            		}
            	});
            }
            // 删除详细类目
            $(document).on('click', '.del-subBusiness', function() {
            	var id = $(this).attr('data-id');
            	$(this).parents('tr').remove();
            	$('#' + id).remove();
            	subBusinesses[$(this).attr('data-code')] = null;
            	resetSubBusiness();
            });
            // 添加品牌// 验证通过回调
        	$('#brandEdit').on('valid.form', function() {
        		var obj = $('#brandEdit').serializeObject();
            	var id = new Date().getTime();
            	addBrand(id, obj);
        		$('[data-dismiss="modal"]').click();
        	});
            // 保存
            $('#brandEdit .submit').on('click', function() {
            	$('#brandEdit').trigger("validate");
            });
            function addBrand(id, obj) {
            	var tr =  '<tr>';
            	$.each(['brandNameZh', 'brandNameEn', 'brandLogo', 'businessType'], function(i, v) {
            		if(i == 2 && obj[v]) {
            			if(obj[v].indexOf('http') > -1) {
                			tr += '<td><img src="' + obj[v] + '" height="25px"></td>';
            			} else {
                			tr += '<td>' + obj[v] + '</td>';
            			}
            		} else {
                		tr += '<td>' + obj[v] + '</td>';
            		}
            	});
            	tr += '<td><button type="button" class="btn bg-teal del-brand" data-id="'+id+'">删除</button></td></tr>';
            	$('.brand-list tbody').append(tr);
            	// 添加到from
            	var hidden = '<input type="hidden" id="'+id+'" name="brands" value="'+JSON.stringify(obj).replace(/\"/g, '&quot;')+'"/>';
            	$('#editForm').append(hidden);
            }
            // 删除品牌
            $(document).on('click', '.del-brand', function() {
            	var id = $(this).attr('data-id');
            	$(this).parents('tr').remove();
            	$('#' + id).remove();
            });
            //
            $('#chkPass').on('click', function() {
            	Util.api.ajax({
        			url: '/company/update',
        			type : "POST",
        			data : JSON.stringify({id : $('#companyEdit [name="id"]').val(), enable: '1'})
            	}, function(data) {
                     Layer.close(Layer.getFrameIndex(window.name));
            	});
            });
        }
    };
    return Controller;
});